package xyf.p01.array_nodelist;

import commons.ListNode;

import java.util.List;

/**
 * ClassName: P0092_Reverse
 * Description:
 * Author: xyf
 * Date: 9/11/22 11:11 AM
 * Version: 1.0
 **/
public class P0092_Reverse
{
    public ListNode reverseBetween(ListNode head, int left, int right)
    {
        ListNode dummyNode = new ListNode();
        dummyNode.next = head;

        //left的前一个节点
        ListNode pre = dummyNode;
        for (int i = 0; i < left - 1; i++)
        {
            pre = pre.next;
        }

        //right
        ListNode rightNode = pre;
        for (int i = 0; i < right - left + 1; i++)
        {
            rightNode = rightNode.next;
        }

        ListNode rightNext = rightNode.next;
        rightNode.next = null;
        ListNode parLeft = pre.next;

        reverse(parLeft);

        pre.next = rightNode;
        parLeft.next = rightNext;
        return dummyNode.next;
    }

    private ListNode reverse(ListNode head)
    {
        ListNode pre = null;
        ListNode cur = head;

        while (cur != null)
        {
            ListNode next = cur.next;
            cur.next = pre;

            pre = cur;
            cur = next;

        }
        return pre;
    }
}
